import React, { useEffect, useState } from 'react';
import { Card, List, Typography, Tag, Empty, Button } from 'antd';
import { useNavigate } from 'react-router-dom';
import { Order, User } from '../../types';
import { Storage, STORAGE_KEYS } from '../../utils/storage';

const { Title, Text } = Typography;

const Orders: React.FC = () => {
  const [orders, setOrders] = useState<Order[]>([]);
  const [user, setUser] = useState<User | null>(null);
  const navigate = useNavigate();

  useEffect(() => {
    const userData = Storage.get<User>(STORAGE_KEYS.USER);
    const orderData = Storage.get<Order[]>(STORAGE_KEYS.ORDERS) || [];
    if (!userData) {
      navigate('/login');
      return;
    }
    setUser(userData);
    setOrders(orderData.filter(order => order.userId === userData.id));
  }, [navigate]);

  const getStatusInfo = (status: Order['status']) => {
    const statusMap = {
      pending: { text: '待付款', color: 'orange' },
      paid: { text: '已付款', color: 'blue' },
      shipped: { text: '已发货', color: 'cyan' },
      delivered: { text: '已送达', color: 'green' },
      cancelled: { text: '已取消', color: 'red' }
    };
    return statusMap[status];
  };

  if (!user) return null;

  return (
    <div style={{ maxWidth: 800, margin: '0 auto' }}>
      <Title level={2}>我的全部订单</Title>
      <Card>
        {orders.length > 0 ? (
          <List
            dataSource={orders}
            renderItem={order => {
              const statusInfo = getStatusInfo(order.status);
              return (
                <List.Item
                  onClick={() => navigate(`/order/${order.id}`)}
                  style={{ cursor: 'pointer' }}
                >
                  <List.Item.Meta
                    title={
                      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                        <Text>订单号：{order.id}</Text>
                        <Tag color={statusInfo.color}>{statusInfo.text}</Tag>
                      </div>
                    }
                    description={
                      <div>
                        <Text>共 {order.items.length} 件商品</Text>
                        <Text style={{ float: 'right' }} className="price-current">
                          ¥{order.totalAmount.toFixed(2)}
                        </Text>
                      </div>
                    }
                  />
                </List.Item>
              );
            }}
          />
        ) : (
          <Empty description="暂无订单" />
        )}
        <div style={{ textAlign: 'center', marginTop: 24 }}>
          <Button type="primary" onClick={() => navigate('/profile')}>返回</Button>
        </div>
      </Card>
    </div>
  );
};

export default Orders;
